//
//  progressOrderDetailsViewController.m
//  QXDLLOrdersModule
//
//  Created by DL on 17/1/7.
//  Copyright © 2017年 DLL. All rights reserved.
//

#import "progressOrderDetailsViewController.h"
#import <QXDriverConfiguration/QXDriverConfiguration.h>
#import "DLLApiManager.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "MapViewRoutePlan.h"
#import <AMapNaviKit/AMapNaviKit.h>
#import <MAMapKit/MAMapKit.h>
#import "LocationManager.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapNaviKit/AMapNaviKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import "ComplaintVC.h"
#import "HeaderMacro.h"
#import "CancelOrderVC.h"
#import <QXDataManager/QXDataManager.h>
#import "CommonUtility.h"
#import "MANaviRoute.h"
#import "NotificationNameManager.h"
#import <QXYueYueModels/QXYYOrderDetailModel.h>
#import <QXYueYueModels/QXYYUserPassengerModel.h>

#import <Mapbox/Mapbox.h>
#import <MapboxDirections/MapboxDirections-Swift.h>
#import "CustomMGLPointAnnotation.h"
#import "CustomMGLAnnotationView.h"
#import <MapboxDirections/MBRouteOptions.h>

#import "MapManager.h"


@interface progressOrderDetailsViewController ()<MAMapViewDelegate , MGLMapViewDelegate>
/// 导航栏左侧按钮
@property (weak, nonatomic) IBOutlet UIBarButtonItem *leftBarButtonItem;
/// 头像
@property (weak, nonatomic) IBOutlet UIImageView *heardImageView;
/// 手机尾号
@property (weak, nonatomic) IBOutlet UILabel *phoneTailNumberLabel;
/// 拨打电话
@property (weak, nonatomic) IBOutlet UIButton *callPhoneButton;
/// 时间图片
@property (weak, nonatomic) IBOutlet UIImageView *timeImageView;
/// 时间
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
/// 类型
@property (weak, nonatomic) IBOutlet UILabel *statusLabel;
/// 订单状态
@property (weak, nonatomic) IBOutlet UILabel *typeLabel;
/// 起点图片
@property (weak, nonatomic) IBOutlet UIImageView *startImageView;
/// 终点图片
@property (weak, nonatomic) IBOutlet UIImageView *endImageView;
/// 起点位置
@property (weak, nonatomic) IBOutlet UILabel *startLabel;
/// 终点位置
@property (weak, nonatomic) IBOutlet UILabel *endLabel;
/// 接机图片
@property (weak, nonatomic) IBOutlet UIImageView *aircraftImageView;
@property (weak, nonatomic) IBOutlet UILabel *aircraftLabel;
@property (weak, nonatomic) IBOutlet UIView *mapBackView;

@property(nonatomic , strong) MapViewRoutePlan *mapViewRoutePlan;


@property (weak, nonatomic) IBOutlet UIView *passengerInfoBackView;

/// 乘客信息的高度
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *passengerInfoViewHeight;


/**
 乘客信息背景视图的高度
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *passengerInfoBackViewHeight;

/**
 如何是接机状态15 , 如果不是-15
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *marginToDividingLine;
/**
 底部按钮的背景视图
 */
@property (weak, nonatomic) IBOutlet UIView *actionBottomView;

/**
 底部按钮背景视图的高度
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *actionBottomViewHeight;


/**
 取消按钮的宽度
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *cancelOrderButtonWidth;


/**
 司机是否取消了当前订单, 默认为NO
 */
@property(nonatomic , assign) BOOL driverIsCancelCurrentOrder;

@property (weak, nonatomic) IBOutlet UIButton *bottomButton;

/// 订单状态码
@property(nonatomic , assign) OrderStatusEnumCode orderStatusEnumCode;

#pragma mark - 地图信息
@property (strong, nonatomic) MAMapView *mapView;

/// 起点大头针
@property(nonatomic , strong) MAPointAnnotation *startAnnotation;

/// 终点大头针
@property(nonatomic , strong) MAPointAnnotation *destinationAnnotation;


@property (weak, nonatomic) IBOutlet NSLayoutConstraint *mapBackViewToTop;



/// mapbox 加载
@property(nonatomic , assign) BOOL isLoadFinished;
/// 当前的导航路线
@property(nonatomic , strong) MBRoute *currentMapBoxRoute;
/// 当前在地图上显示的路线
@property(nonatomic , strong) MGLPolyline *currentMapboxRouteLine;

/// 起点注释
@property(nonatomic , strong) CustomMGLPointAnnotation *orginPinMapbox;
/// 终点注释
@property(nonatomic , strong) CustomMGLPointAnnotation *destPinMapbox;
/// mapbox 地图
@property(nonatomic , strong) MGLMapView *mapboxMapView;


@end

@implementation progressOrderDetailsViewController

+ (instancetype)shareSelf {
    return [[UIStoryboard storyboardWithName:@"Orders" bundle:nil] instantiateViewControllerWithIdentifier:@"progressOrderDetailsViewController"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configureDefaultsAttributes];
    
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self registerNotificationDriverCancelOrder]; // 司机取消订单通知
}

- (void)viewDidDisappear:(BOOL)animated {
    
    [super viewDidDisappear:animated];
    
    [self cancelNotification];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    if ([MapManager shareManager].currentMapType == MapTypeMapBox) {
        
        if (self.isLoadFinished == NO) {
            [self initMapboxMapView];
            self.isLoadFinished = YES;
        }
    }else if ([MapManager shareManager].currentMapType == MapTypeGD) {
        
        if (self.isLoadFinished == NO) {
            
            [self configureMapView];
            self.isLoadFinished = YES;
        }
    }
}

#pragma mark - 配置 mapbox 的地图
- (void)initMapboxMapView {
    
    self.mapboxMapView = [[MGLMapView alloc] initWithFrame:CGRectMake(0, 0, self.mapBackView.frame.size.width, self.mapBackView.frame.size.height)];
    self.mapboxMapView.delegate = self;
    self.mapboxMapView.showsUserLocation = NO;
    self.mapboxMapView.userInteractionEnabled = NO;
    
    [self.mapBackView addSubview:self.mapboxMapView];
    
    self.mapboxMapView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    [self.mapboxMapView bringSubviewToFront:self.mapBackView];
    
    CustomMGLPointAnnotation *orginPin = [[CustomMGLPointAnnotation alloc] init];
    orginPin.identifier = @"起点";
    orginPin.title = @"起点";
    orginPin.coordinate = CLLocationCoordinate2DMake(self.ordersDetailsModel.originLat, self.ordersDetailsModel.originLng);

    [self.mapboxMapView addAnnotation:orginPin];

    [self.mapboxMapView setCenterCoordinate:orginPin.coordinate zoomLevel:10 animated:YES];

    
}

#pragma mark - 配置地图属性
- (void)configureMapView {
    
    self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, self.mapBackView.frame.size.width, self.mapBackView.frame.size.height)];
    [self.mapBackView addSubview:self.mapView];
    self.mapView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    self.mapView.delegate = self;
    self.startAnnotation = [[MAPointAnnotation alloc] init];
    self.destinationAnnotation = [[MAPointAnnotation alloc] init];
    self.mapView.userInteractionEnabled = NO;
    self.mapView.showsUserLocation = NO;
    
    
    if (![LocationManager shareManager].userLocationModel) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            MBProgressHUD *mb = [MBProgressHUD showWithText:@"地图定位失败" onView:self.view hiddenDuration:2.0];
            mb.userInteractionEnabled = NO;
        });
        
    }else {
        
        MAPointAnnotation *annotation_Origin = [[MAPointAnnotation alloc] init];
        annotation_Origin.title = @"起点";
        annotation_Origin.coordinate = CLLocationCoordinate2DMake(self.ordersDetailsModel.originLat, self.ordersDetailsModel.originLng);
        NSArray *annotationArray = @[annotation_Origin];
        
        [self.mapView addAnnotations:annotationArray];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.mapView showAnnotations:annotationArray edgePadding:UIEdgeInsetsMake(80, 80, 230, 80) animated:YES];
            [self.mapView setZoomLevel:16];
        });
    }
}

#pragma mark - 地图 代理 方法
static NSString *DriverIdentifier = @"Driver";
static NSString *PinIdentifier = @"Annotation";
#if MapTypeMicro == 1 // 高德地图
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    
    
    if ([annotation isKindOfClass:[MAUserLocation class]])
    {
        
        MAAnnotationView *driverLocation = [mapView dequeueReusableAnnotationViewWithIdentifier:DriverIdentifier];
        
        if (driverLocation == nil) {
            
            driverLocation = [[MAAnnotationView alloc] initWithAnnotation:annotation
                                                          reuseIdentifier:DriverIdentifier];
        }
        
        driverLocation.image = [UIImage imageNamed:@""];
        
        return driverLocation;
    }
    
    
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        
        MAAnnotationView *poiAnnotationView = (MAAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:routePlanningCellIdentifier];
        if (poiAnnotationView == nil)
        {
            poiAnnotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation
                                                             reuseIdentifier:routePlanningCellIdentifier];
        }
        
        poiAnnotationView.canShowCallout = YES;
        
        if ([[annotation title] isEqualToString:@"起点"]) {
            
            poiAnnotationView.image = [QXDriverConfiguration imageWithName:@"public_pic_qidian"];
            
        }else if([[annotation title] isEqualToString:@"终点"])
        {
            
            poiAnnotationView.image = [QXDriverConfiguration imageWithName:@"public_pic_zhongdian"];
        }
        
        return poiAnnotationView;
    }
    
    return nil;
}

#elif MapTypeMicro == 2 // MapBox 地图

- (MGLAnnotationView *)mapView:(MGLMapView *)mapView viewForAnnotation:(id<MGLAnnotation>)annotation {
    
    
    if ([annotation isKindOfClass:[CustomMGLPointAnnotation class]]) {
        
        CustomMGLAnnotationView *annotationView = (CustomMGLAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:PinIdentifier];
        
        if (annotationView == nil) {
            
            annotationView = [[CustomMGLAnnotationView alloc] initWithReuseIdentifier:PinIdentifier];
            annotationView.frame = CGRectMake(0, 0, 30, 30);
        }
        
        CustomMGLPointAnnotation *customPointAnnotation = (CustomMGLPointAnnotation *)annotation;
        
        if (customPointAnnotation != nil) {
            
            annotationView.backgroundColor = [UIColor clearColor];
            if ([customPointAnnotation.identifier isEqualToString:@"起点"]) {
                
                annotationView.imageView.image = [QXDriverConfiguration imageWithName:@"public_pic_qidian"];
                
            }else if ([customPointAnnotation.identifier isEqualToString:@"终点"]) {
                
                annotationView.imageView.image = [QXDriverConfiguration imageWithName:@"public_pic_zhongdian"];
            }
        }
        
        return annotationView;
    }
    
    return nil;
}

#endif


#pragma mark - 配置默认属性
- (void)configureDefaultsAttributes {
    self.leftBarButtonItem.image = [QXDriverConfiguration imageWithName:@"nav_icon_back_white"];
    [self.callPhoneButton setImage:[QXDriverConfiguration imageWithName:@"public_call"] forState:UIControlStateNormal];
    self.timeImageView.image = [QXDriverConfiguration imageWithName:@"puclic_time_gray"];
    self.aircraftImageView.image = [QXDriverConfiguration imageWithName:@"puclic_plane_gray"];
    
    // 添加数据
    if (self.ordersDetailsModel != nil || self.userPassengerModel != nil) {
        [self userPassengerAndOrdersDetails];
    }else {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self getOrdersDetails];
        });
        
    }
    
    self.driverIsCancelCurrentOrder = NO;
    
    // 初始化订单状态
    self.orderStatusEnumCode = self.ordersDetailsModel.subStatus;
    self.mapViewRoutePlan.orderStatusEnumCode = self.ordersDetailsModel.subStatus;
}


/**
 注册司机取消订单的通知
 */
- (void)registerNotificationDriverCancelOrder {
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(driverCancelOrderAction:) name:NotificationName_DriverCancelOrder object:nil];
}




/**
 司机取消订单通知Action
 */
- (void)driverCancelOrderAction:(NSNotification *)aNotification {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        self.cancelOrderButtonWidth.constant = -0.5; // 隐藏取消订单按钮
        self.actionBottomViewHeight.constant = 20.0; // 设置底部按钮的高度
        self.actionBottomView.hidden = YES; // 隐藏底部的视图
        self.driverIsCancelCurrentOrder = YES; // 司机取消了当前订单
        self.passengerInfoBackViewHeight.constant = self.passengerInfoBackViewHeight.constant - 55;
        self.typeLabel.text = @"已取消";
    });
    

}


#pragma mark - 获取数据 页面赋值
- (void)userPassengerAndOrdersDetails {
    
    self.passengerInfoBackView.layer.cornerRadius = 2.0;
    self.passengerInfoBackView.layer.masksToBounds = YES;
    
    self.startImageView.layer.cornerRadius = 2.5;
    self.startImageView.layer.masksToBounds = YES;
    
    self.endImageView.layer.cornerRadius = 2.5;
    self.endImageView.layer.masksToBounds = YES;
    
    self.heardImageView.layer.cornerRadius = 23;
    self.heardImageView.layer.masksToBounds = YES;
    
    if (![self.userPassengerModel.face isKindOfClass:[NSNull class]] && self.userPassengerModel.face.length > 0) { // 如果值非空,并且长度大于0
        
        NSURL *url = [NSURL URLWithString:self.userPassengerModel.face];
        [self.heardImageView sd_setImageWithURL:url placeholderImage:[QXDriverConfiguration imageWithName:@"tongyong_chencheren_icon"]];
    }else {
        
        self.heardImageView.image = [QXDriverConfiguration imageWithName:@"tongyong_chencheren_icon"];
    }
    
    self.statusLabel.layer.cornerRadius = 4.0;
    self.statusLabel.layer.masksToBounds = YES;
    self.statusLabel.layer.borderWidth = 0.5;
    self.statusLabel.layer.borderColor = [UIColor colorWithRed:158 / 255.0 green:167 / 255.0 blue:177 / 255.0 alpha:1.0].CGColor;
    
    self.bottomButton.layer.cornerRadius = 5.0;
    self.bottomButton.layer.masksToBounds = YES;
    
    self.cancelOrderButtonWidth.constant = ([UIScreen mainScreen].bounds.size.width - 20 - 1) / 3.0;

    
    // 截取
    NSString *phone = [self.userPassengerModel.mobile substringFromIndex:7];
    self.phoneTailNumberLabel.text = [NSString stringWithFormat:@"尾号%@",phone];
    // 时间
    NSTimeInterval interval = self.ordersDetailsModel.deparTime / 1000.0;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
    NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
    [objDateformat setDateFormat:@"M月dd日  hh:mm"];
    self.timeLabel.text  = [objDateformat stringFromDate: date];
    
    self.aircraftLabel.hidden = YES;
    self.aircraftImageView.hidden = YES;
    /// 订单类型（行程）：1 出租车；2 专车； 3 拼车； 4 接送机；5 日租/半日租
    if (self.ordersDetailsModel.typeTrip.integerValue == 1) {

        self.statusLabel.text = @"出租车    ";
        self.statusLabel.hidden = YES;
        self.passengerInfoBackViewHeight.constant = 205;
        self.marginToDividingLine.constant = -15;
        
    }else if (self.ordersDetailsModel.typeTrip.integerValue == 2) {
        self.statusLabel.text = @"专车    ";
        self.statusLabel.hidden = YES;
        self.passengerInfoBackViewHeight.constant = 205;
        self.marginToDividingLine.constant = -15;
    }else if (self.ordersDetailsModel.typeTrip.integerValue == 3) {
        self.statusLabel.text = @"拼车    ";
        self.statusLabel.hidden = YES;
        self.passengerInfoBackViewHeight.constant = 205;
        self.marginToDividingLine.constant = -15;
    }else if (self.ordersDetailsModel.typeTrip.integerValue == 4) {
        self.statusLabel.text = @"快车    ";
        self.statusLabel.hidden = YES;
        self.passengerInfoBackViewHeight.constant = 205;
        self.marginToDividingLine.constant = -15;
    }
    
    else if (self.ordersDetailsModel.typeTrip.integerValue == 5) { // 货的
        
        self.statusLabel.text = @"货的    ";
        self.statusLabel.hidden = YES;
        self.passengerInfoBackViewHeight.constant = 205;
        self.marginToDividingLine.constant = -15;
    }else if (self.ordersDetailsModel.typeTrip.integerValue == 6) { // 骑手
        
        self.statusLabel.text = @"骑手    ";
        self.statusLabel.hidden = YES;
        self.passengerInfoBackViewHeight.constant = 185;
        self.marginToDividingLine.constant = -15;
    }else if (self.ordersDetailsModel.typeTrip.integerValue == 7) { // 搬家
        
        self.statusLabel.text = @"搬家    ";
        self.statusLabel.hidden = YES;
        self.passengerInfoBackViewHeight.constant = 205;
        self.marginToDividingLine.constant = -15;
    }

    
    if ([self.ordersDetailsModel.typeTime isEqualToString:@"3"] || [self.ordersDetailsModel.typeTime isEqualToString:@"4"]) {
        
        self.statusLabel.hidden = NO;
        self.statusLabel.text = @"包车    ";
        
    }
    
    self.statusLabel.layer.cornerRadius = 4;
    self.statusLabel.layer.masksToBounds = YES;
    
    self.startLabel.text = self.ordersDetailsModel.originAddress;
    
    if ([self.ordersDetailsModel.destAddress isKindOfClass:[NSNull class]] || self.ordersDetailsModel.destAddress.length <= 0) {
        
        self.endLabel.text = @"";
    }else {
        
        self.endLabel.text = self.ordersDetailsModel.destAddress;
    }
    
    self.mapBackViewToTop.constant = -140;
}
#pragma mark -获取订单详情
- (void)getOrdersDetails {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:self.ordersDetailsModel.uuid forKey:@"orderUuid"];
    
    __weak typeof(self) weakSelf = self;
    
    [DLLApiManager getTheOrderDetailsWithParameters:dic success:^(id data) {
        
        __strong typeof(self) strongSelf = weakSelf;
        
        if (NetWork_Success) {
            strongSelf.ordersDetailsModel = [QXYYOrderDetailModel QXYY_objectWithKeyValues:data[@"data"]];
            strongSelf.userPassengerModel = [QXYYUserPassengerModel QXYY_objectWithKeyValues:data[@"data"][@"passenger"]];
            [strongSelf userPassengerAndOrdersDetails];
            
        }else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showWithText:[NSString stringWithFormat:@"%@",data[@"msg"]] onView:strongSelf.view hiddenDuration:1];
            });
        }
        
    } failure:^(NSError *error) {
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD showWithText:@"获取订单详情失败" onView:strongSelf.view hiddenDuration:1];
        });
    }];
}

#pragma mark - 联系乘客
- (IBAction)connectPassenger:(UIButton *)sender {
    
    NSString *phone = self.userPassengerModel.mobile;
    if (phone != nil) {
        
        NSString *telUrl = [NSString stringWithFormat:@"telprompt:%@",phone];
        
        NSURL *url = [[NSURL alloc] initWithString:telUrl];
        
        [[UIApplication sharedApplication] openURL:url];
    }
}

#pragma mark -客服
- (IBAction)customerServiceAction:(UIButton *)sender {
    
//    NSString *phone = [[NSUserDefaults standardUserDefaults] valueForKey:User_KeyWord_CustomerServiceTel];
    
    NSString *phone = [QXDataManager getValueForKey:User_KeyWord_CustomerServiceTel];
    
    if (phone != nil) {
        
        NSString *telUrl = [NSString stringWithFormat:@"telprompt:%@",phone];
        
        NSURL *url = [[NSURL alloc] initWithString:telUrl];
        
        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
            
            sender.userInteractionEnabled = YES;
        }];
        sender.userInteractionEnabled = NO;
    }
}

#pragma mark -投诉
- (IBAction)complaintsAction:(id)sender {
    
    ComplaintVC *complaintVC = [ComplaintVC initComplaintVC];
    complaintVC.title = @"投诉";
    
    complaintVC.orderUuid = self.ordersDetailsModel.uuid;
    
    [self.navigationController pushViewController:complaintVC animated:YES];
    
}

#pragma mark -继续行程
- (IBAction)continueJourneyAction:(id)sender {

    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -取消行程
- (IBAction)cancelTheTripAction:(id)sender {
    
    CancelOrderVC *cancelOrderVC = [CancelOrderVC initCancelOrderVC];
    cancelOrderVC.title = @"取消订单";
    cancelOrderVC.orderUuid = self.ordersDetailsModel.uuid;
    [self.navigationController pushViewController:cancelOrderVC animated:YES];
}

#pragma mark -导航条左侧按钮
- (IBAction)leftBarButtonItemAction:(id)sender {
    
    
    if (self.driverIsCancelCurrentOrder) { // 司机取消了当前订单
        
        [self.navigationController popToRootViewControllerAnimated:YES];
    }else {
        
        [self.navigationController popViewControllerAnimated:YES];
    }
}


- (void)cancelNotification {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NotificationName_DriverCancelOrder object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NotificationName_LongLink_PassengerCancelOrder object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NotificationName_LongLink_BackShutDownOrder object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
